package com.effects;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;

/**
 * @author sad
 */
public class EqualizerEffect extends BasicEffect {

    @Override
    public String getEffectName() {
        return "Equalizer";
    }

    @Override
    public String getId() {
        return "equalizer";
    }

    private final double[] equalizer = new double[11];
    private final double[] oldEqualizer = new double[11];

    @Override
    public BufferedImage getImage(byte[] pcm) {
        double[] tSpectrum = spectrum(pcm);
        if (tSpectrum == null) {
            return null;
        }
        double factor = equalizer.length / 11;
        int sample = 1;
        double min = 999999;
        double max = 0;
        for (int j = 0; j < equalizer.length; j++, sample += factor) {
            equalizer[j] = tSpectrum[sample];
            if (equalizer[j] < min) {
                min = equalizer[j];
            }
            if (equalizer[j] > max) {
                max = equalizer[j];
            }
        }

        max -= min;
        for (int i = 0; i < equalizer.length; i++) {
            equalizer[i] = (equalizer[i] - min) / max;
        }

        Graphics g = image.getGraphics();
        g.setColor(Color.black);
        g.fillRect(0, 0, image.getWidth(), image.getHeight());
        g.setColor(Color.BLUE);
        tSpectrum[0] /= 5;
        int height = image.getHeight();
        float x = 0;
        float width = image.getWidth() / 11;
        for (int i = 0; i < equalizer.length; i++) {
            if(i==10){
                i=i;
            }
            double r = equalizer[i];
            double old = oldEqualizer[i];
            if (old < r) {
                old=r;
                oldEqualizer[i]=old;
            }else{
                oldEqualizer[i]-=0.1;
                if(oldEqualizer[i]<r){
                    oldEqualizer[i]=r;
                }
            }
            double nold=(old*34);
            double nr = (r * 34);
            g.setColor(Color.BLUE);
            g.fillRect((int) x, height - (int) nr, (int) (width), height);
            g.setColor(Color.RED);
            g.drawLine((int) x, height - (int) nold-1, (int) (x + width)-1, height - (int) nold-1);
            x += width;
        }

        return image;
    }
}
